const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const {koaBody} = require('koa-body');
const jwt = require('koa-jwt')
const db = require('./db/db');


const cors = require('koa-cors');
const session = require('koa-session');


const users = require('./routes/users')
const index = require('./routes/index')

// error handler
onerror(app)

app.use(require('koa-static')(__dirname + '/public'))

// app.use(cors());
//解决跨域问题
app.use(async (ctx, next) => {
  if (ctx.method === 'OPTIONS') {
    // 设置 CORS 头信息
    ctx.set('Access-Control-Allow-Origin', 'http://localhost:8080');
    ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Authorization, Response-Type');
    ctx.set('Access-Control-Allow-Credentials', 'true');
    ctx.status = 204; // No Content
  } else {
    await next();
  }
});
app.use(cors({
  origin: 'http://localhost:8080',
  credentials: true
}));

app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: __dirname + '/public', // 定义文件上传的目录
    keepExtensions: true // 保留文件扩展名
  }
}));
// app.use(koaBody({ multipart: true }));

app.keys = ['MY-SECRET-KEY']; // 设置用于签名和加密session的密钥
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
// app.use(bodyparser());


app.use(json())
app.use(logger())
app.use(jwt({ secret: 'test' }).unless({ path: [/^\/login$/, /^\/captcha$/, /^\/public/ ]} ))

//添加密钥
app.use(session({
  key: 'koa:sess', // cookie key (default is koa:sess)
  maxAge: 86400000, // session过期时间，默认是一天
  overwrite: true,
  httpOnly: true,
  signed: true,
}, app));
app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(async(ctx, next) => {
  ctx.db = db;
  await next();
})

app.use(users.routes(), users.allowedMethods())
app.use(index.routes(), index.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app